import React, { useState, useEffect } from 'react';
import { Row, Col, Button, Input, Switch, Divider, Table, Popconfirm, Form, message } from 'antd';
import { connect, history,useDispatch } from 'umi';
import { PlusOutlined } from '@ant-design/icons';
import PageTopFormContent from '../../../components/PageTopFormContent';
import PaginationCommon from '../../../components/PaginationCommon';
import AppManageAddEdit from './components/appmanageAddEdit';

import styles from './AppManage.less';

const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};

const AppManage = (props) => {
  const {appManageModel, loading: { effects } } = props;
  const { appList,appTotal } = appManageModel;
  const [form] = Form.useForm();
  const dispatch = useDispatch();

  const [formData,setFormData] = useState({});
  const [currentPage,setCurrentPage] = useState(1);
  const [currentPageSize,setCurrentPageSize] = useState(10);

  const [drawerVisible, setDrawerVisible] = useState(false);
  const [drawerType, setDrawerType] = useState('add');
  const [currentEditData, setCurrentEditData] = useState({});
  const [functionData,setFunctionData] = useState([]);
  const [sort, setSort] = useState();

  const getAppList = () => {
    const submitData = {
      pageIndex: currentPage,
      pageSize: currentPageSize,
      ...formData,
      sortMap:sort
    }
    dispatch({
      type: 'appManageModel/getAppList',
      payload: submitData
    })
  }
  const getFunctionList = () => {
    dispatch({
      type: 'appManageModel/getFunctionList',
      payload:{}
    }).then(res => {
      const { code, data, message:errMsg } = res;
      if(code === 0 ){
        setFunctionData(data);
      }else{
        message.error(errMsg);
      }
    })
  }

  useEffect(() => { getAppList(),getFunctionList() }, [currentPage,currentPageSize,formData,sort]);

  const handleSearch = () => {
    const { validateFields } = form;
    validateFields().then((values) => {
      const param = { ...values }
      setFormData(param);
      setCurrentPage(1);
    });
  };

  const handleReset = () => {
    form.resetFields();
    setCurrentPage(1);
    setFormData({});
  };

  const handleCloseDrawer = ( update = false ) => {
    setDrawerVisible(false);
    setCurrentEditData({});
    if(update){
      handleSearch();
    }
  };

  const handleDelete = (id) => {
    dispatch({
      type: 'appManageModel/deleteAuth',
      payload: [id]
    }).then(res => {
      const { code, message: errMsg} = res;
      if(code ===0 ){
        message.success("删除成功");
        handleSearch();   
      }else{
        message.error(errMsg);
      }
    })
  };

  // 展示右测抽屉
  const handleShowDrawer = (type, record) => {
    setDrawerType(type);
    setDrawerVisible(true);
    if (record) {
      setCurrentEditData(record);
    }
  };

  const handleTableChange = (_, filters, sorter) => {
    if (JSON.stringify(sorter) !== '{}') {
      const { field, order } = sorter;
      setSort({[`${field}`] : order === 'ascend' ? 'asc' : 'desc'});
    }
  };

  const onSwitchChange = (bool,record) => {
    let appId = record.id;
    if(bool){
      dispatch({
        type:'appManageModel/openStatus',
        payload: {appId}
      }).then(res =>{
        const { code, message:errMsg} = res;
        if(code === 0){
          message.success("开放授权！");
          handleSearch();
        }else{
          message.error(errMsg);
        }
      })
    }else{
      dispatch({
        type:'appManageModel/closeStatus',
        payload: {appId}
      }).then(res => {
        const { code, message:errMsg} = res;
        if(code === 0){
          message.success("关闭授权！");
          handleSearch();
        }else{
          message.error(errMsg);
        }
      })
    }
  }

  const showDetail = record => {
    history.push({
      pathname: '/authoritymanage/appmanage/appdetail',
      state:{
        record: record,
      }
    })
  }

  const handlePaginationChange = (page, pageSize) => {
    setCurrentPage(page);
    setCurrentPageSize(pageSize);
  } 

  const columns = [
    {
      title: '应用编码',
      dataIndex: 'appCode',
      key: 'appCode',
    },
    {
      title: '应用名称',
      dataIndex: 'appName',
      key: 'appName',
    },
    {
      title: '已开通服务',
      dataIndex: 'functionNameStr',
      key: 'functionNameStr',
      render: (text,record) =>(record.functionList?record.functionList.map(item => item.functionName).join('、'):null)
    },
    {
      title: '状态',
      dataIndex: 'appState',
      key: 'appState',
      render: (text, record) => (
        <Switch
          checkedChildren={record.appState === 1 ? '开' : '关'}
          unCheckedChildren={record.appState !== 1 ? '关' : '开'}
          defaultChecked={record.appState}
          onChange={(bool)=>onSwitchChange(bool,record)}
        />
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreated',
      key: 'gmtCreated',
      sorter: true,
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => (
        <div>
          <a onClick={() => showDetail(record)}>详情</a>
          <Divider type="vertical" />
          <a onClick={() => handleShowDrawer('edit', record)}>修改</a>
          <Divider type="vertical" />
          <Popconfirm title="你确定要删除该应用信息吗?" onConfirm={() => handleDelete(record.id)}>
            <a>删除</a>
          </Popconfirm>
        </div>
      ),
    },
  ];

  return (
    <div className={styles.root}>
      <PageTopFormContent
        title="第三方应用管理"
        content={(
          <Form {...layout} form={form} name="advanced_search">
            <Row gutter={[32, 16]}>
              <Col className="gutter-row" span={6}>
                <Form.Item name="appCodeKey" label="应用编码">
                  <Input placeholder="请输入编码" />
                </Form.Item>
              </Col>
              <Col className="gutter-row" span={6}>
                <Form.Item name="appNameKey" label="应用名称">
                  <Input placeholder="请输入用户账号" />
                </Form.Item>
              </Col>
              <Col className="gutter-row" span={6}>
                <Form.Item wrapperCol={{ ...layout.wrapperCol }}>
                  <Button type="primary" onClick={handleSearch}>
                    查询
                  </Button>
                  <Button style={{ marginLeft: 16 }} onClick={handleReset}>
                    重置
                  </Button>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        )}
      />
      <div className={styles.tableWapper}>
        <div className={styles.listHead}>
          <div className={styles.listTitle}>应用列表</div>
          <Button type="primary" onClick={() => handleShowDrawer('add')}>
            <PlusOutlined />
            {' '}
            添加应用
          </Button>
        </div>
        <div className={styles.listTable}>
          <Table
            rowKey="id"
            columns={columns}
            dataSource={appList}
            current={currentPage}
            pageSize={currentPageSize}
            pagination={false}
            loading={effects['appManageModel/getAppList']}
            onChange={handleTableChange}
          />
          <PaginationCommon style={{ textAlign: 'right' }} 
          total = {appTotal}
          current={currentPage}
          pageSize={currentPageSize}
          onChange={handlePaginationChange}
        />
        </div>
      </div>
      {drawerVisible && (
        <AppManageAddEdit
          drawerType={drawerType}
          editData={currentEditData}
          handleCloseDrawer={handleCloseDrawer}
          functionData = {functionData}
        />
      )}
    </div>
  );
};

export default connect(state => state)(AppManage);
